﻿/* 
 *  <copyright file="NextAtTargetCmp.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System.Collections.Generic;
using Microsoft.Xna.Framework;
using SobrietyEngine.Actor;
using SobrietyEngine.Geometry;

namespace SobrietyEngine.Components.Paths
{
    public class ManualFollower : BaseComponent, IComponent
    {
        IActor startingNode;
        PathNodeCmp targetPathNodeCmp;
        IPosition myPosCmp;
        IMovement myMoverCmp;
        float delta = 0.05f; //radius around pathnode we can acceptably be to call it a 'hit'

        public ManualFollower()
            : base()
        {
        }

        public ManualFollower(IActor startingNodeActor)
            : base()
        {
            startingNode = startingNodeActor;
        }

        public override bool InitComponent()
        {
            base.InitComponent();

            targetPathNodeCmp = startingNode.Get<PathNodeCmp>();
            myPosCmp = Actor.Get<IPosition>();
            myMoverCmp = Actor.Get<IMovement>();

            if (targetPathNodeCmp == null || myPosCmp == null || myMoverCmp == null)
            {
                Logging.Logger.GetSingleton().WriteError(this, "failed to find required components");
                return false;
            }

            myMoverCmp.SetTarget(targetPathNodeCmp.PositionV2);            

            return true;
        }

        public override void Update(GameTime ElapsedTime)
        {
            //check if we are at our target
            if (Intersect.PointPoint(myPosCmp.PositionV3, targetPathNodeCmp.PositionV3, delta))
            {
                //we are at our target, select the next taget mode and get to moving
                List<IActor> nextNodes = targetPathNodeCmp.GetNextPathNodeActors();
                if (nextNodes.Count == 0)
                    Logging.Logger.Error(this, "next path node not found@!");

                //else, we need to pick a node. lets just grab the first one returned.
                targetPathNodeCmp = nextNodes[0].Get<PathNodeCmp>();
                
                //and set our mover to startheading towards the target, if we have a mover
                if (myMoverCmp != null)
                    myMoverCmp.SetTarget(targetPathNodeCmp.PositionV2);
            }
        }
    }
}